import datetime

from case.api.serializers import CaseProgressSerializer
from case.models import Case, CustomerCase
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer


class WxCaseSerializer(ModelSerializer):
    """
    案件登记
    """
    case_type_name = serializers.CharField(source="get_case_type_display", read_only=True)
    user_name = serializers.CharField(source="user.real_name", read_only=True)
    lead_lawyer_name = serializers.CharField(source="lead_lawyer.real_name", read_only=True)
    lead_lawyer_tel = serializers.CharField(source="lead_lawyer.telephone", read_only=True)
    assist_lawyer_name = serializers.CharField(source="assist_lawyer.real_name", read_only=True)
    assist_lawyer_tel = serializers.CharField(source="assist_lawyer.telephone", read_only=True)
    third_lawyer_name = serializers.CharField(source="third_lawyer.real_name", read_only=True)
    third_lawyer_tel = serializers.CharField(source="third_lawyer.telephone", read_only=True)
    progresses = CaseProgressSerializer(many=True, read_only=True)
    current_phase = serializers.SerializerMethodField()     # 当前案件阶段
    is_final = serializers.SerializerMethodField()          # 结案标志
    recvtime = serializers.SerializerMethodField()          # 接收时间

    class Meta:
        model = Case
        exclude = ['recv_time', 'update_time', 'add_time']

    def get_current_phase(self, obj):
        phase = self.recent_phase(obj)
        if phase and phase.progress:
            return phase.progress.name
        return ""

    def get_is_final(self, obj):
        phase = self.recent_phase(obj)
        if phase and phase.progress:
            return phase.progress.is_final
        return False

    def recent_phase(self, obj):
        return obj.progresses.all().order_by("-add_time").first()

    def get_recvtime(self, obj):
        return datetime.datetime.strftime(obj.add_time, '%Y-%m-%d')


class CustomerCaseSerializer(ModelSerializer):
    """客户案件"""
    case = WxCaseSerializer(read_only=True)

    class Meta:
        model = CustomerCase
        exclude = ["update_time", "add_time"]